package com.dineroquegastar.urule.controller;

import com.bstek.urule.console.AdminEntity;
import com.dineroquegastar.urule.service.AdminService;
import com.dineroquegastar.urule.utils.Sha1Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/user")
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private Sha1Utils sha1Utils;

    @SneakyThrows
    @PostMapping("/login")
    public String login(String username,
                        String password,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        String error = "";
        AdminEntity adminEntity = adminService.login(username);
        if (adminEntity == null) {
            log.error("user {} login failed, user not exists", username);
            error = "用户不存在";
        } else if (!adminEntity.getPassword().equals(sha1Utils.Sha1(password))) {
            log.error("user {} login failed, invalid password", username);
            error = "密码错误";
        }
        request.setAttribute("error", error);
        if (error == "") {
            request.getSession().setAttribute("admin", adminEntity);
            response.sendRedirect("/urule/frame");
        }
        return "login";
    }
}
